import java.util.HashMap;
import java.util.Map;

class Solution {
    public static int subarraySum(int[] nums, int k) {
        int n = nums.length;

        int[] dp = new int[n + 1];
        Map<Integer, Integer> map = new HashMap<>(); //key 为 dp 中的元素，value 为元素对应的个数
        for (int i = 1; i < n + 1; i++) {
            dp[i] = dp[i - 1] + nums[i - 1];
            map.put(dp[i], map.getOrDefault(dp[i], 0) + 1);
        }

        int ret = 0;
        for (int i = 0; i < n; i++) {
            ret += map.getOrDefault(dp[i] + k, 0);
        }

        return k == 0 ? ret / 2 : ret;
    }

    public static void main(String[] args) {
        System.out.println(subarraySum(new int[]{-1, -1, 1}, 0));
    }
}